#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from dws.commons.log_utils import log
from common.common import exter_attack, output_result_file
from common.common_models import SubJobModel
from common.const import SubJobPolicyEnum
from dws.commons.const import SubJobType
from dws.restore.parse_restore_job import ParseRestoreJobParam


def gen_sub_job(pid, job_id):
    sub_job_list = [
        SubJobModel(
            jobId=job_id, jobType=SubJobType.BUSINESS_SUB_JOB.value, jobName="white_list_subtask", jobPriority=1,
            policy=SubJobPolicyEnum.EVERY_NODE_ONE_TIME_SKIP_OFFLINE.value, ignoreFailed=True
        ).dict(by_alias=True),
        SubJobModel(
            jobId=job_id, jobType=SubJobType.BUSINESS_SUB_JOB.value, jobName="restore_subtask", jobPriority=2,
            policy=SubJobPolicyEnum.ANY_NODE.value, ignoreFailed=False
        ).dict(by_alias=True),
        SubJobModel(
            jobId=job_id, jobType=SubJobType.BUSINESS_SUB_JOB.value, jobName="clean_subtask", jobPriority=3,
            policy=SubJobPolicyEnum.EVERY_NODE_ONE_TIME_SKIP_OFFLINE.value, ignoreFailed=True
        ).dict(by_alias=True)
    ]
    output_result_file(pid, sub_job_list)


@exter_attack
def do_exec(pid):
    restore_job_param = ParseRestoreJobParam(pid)
    job_id = restore_job_param.get_main_job_id()

    try:
        gen_sub_job(pid, job_id)
    except Exception as err_str:
        log.error(f"Generate sub job failed end with {err_str}, pid: {pid}, job id: {job_id}")
        return False
    log.info(f"Generate sub job suc, pid: {pid}, job id: {job_id}")
    return True


if __name__ == '__main__':
    if len(sys.argv) < 2:
        log.error("Param is wrong.")
        sys.exit(1)

    try:
        do_exec(sys.argv[1])
    except Exception as err:
        log.error(f"Err: {err}, pid: {sys.argv[1]}")
        sys.exit(0)

    sys.exit(0)
